<template>
  <view class="index-page">
    <hs-status-bar></hs-status-bar>
    <top-bar :title="'AI定制'" :haveBack="false"></top-bar>

    <hs-phoneModel :activeMaterialName="activeMaterialName" material-type="example" :materialList="materialList"
      @handleSelectModel="selectModel" @handleSelectMaterial="selectMaterial" ref="phoneModel"></hs-phoneModel>
    <view class="tabs hs-flex-center">
      <view class="nav-container">
        <view class="primary-nav">
          <view v-for="(item, index) in tabsList" :key="index" class="nav-item" @click="toggleSubNav(index)"
            :class="{ active: mainIndex === index }">
            {{ item.name }}
            <view class="hs-margin-row-10"
              :style="{ transform: `rotate(${mainIndex === index ? 90 : 0}deg)`, color: mainIndex === index ? '#3C4242' : '#807D7E' }">
              <image :src="`/static/images/icon/${mainIndex === index ? 'arrow-right-select' : 'arrow-right'}.png`"
                style="width: 35rpx;height: 35rpx;" mode="aspectFit"></image>
            </view>
          </view>
        </view>

        <view v-if="isShowSubNav" class="sub-nav">
          <view v-for="(subItem, i) in tabsList[mainIndex].children" :key="i" class="sub-nav-item"
            :class="{ 'sub-active': i === subIndex }" @click.stop="switchSubTab(subItem)"
            style="position: relative; z-index: 10;">
            {{ subItem.name }}
          </view>
        </view>
      </view>
    </view>
    <scroll-view class="scroll-box" :refresher-triggered="triggered" :refresher-threshold="500"
      @refresherrefresh="onRefresh" @refresherrestore="onRestore" :refresher-enabled="mainIndex == 0" scroll-y
      @scrolltolower="scrolltolower">
      <view class="">
        <view class="cases" v-if="exampleList.length > 0">
          <view class="cases-item" v-for="item of exampleList" :key="item.id">
            <navigator
              :url="`/pages/example/casesView?phoneModelId=${phoneModelId}&sort=${item.sort}&activeMaterial=${activeMaterial}&activeStyleList=${activeStyleList}&type=${listType}&algorithmName=${algorithmName}`">
              <image :src="item.imageUrl" mode="aspectFit" class="img" :class="{ loading: !item.isLoaded }"
                @load="handleImageLoad(item)" :style="{ background: item.isLoaded ? 'transparent' : '#eee' }" lazy-load>
              </image>
              <view class="price"> ￥{{ item.price || "" }} </view>
            </navigator>
          </view>
        </view>
        <view class="hs-p-b-20" v-if="!isEmpty">
          <u-loadmore :status="status" />
        </view>
        <u-empty v-if="isEmpty" mode="data" text="暂无数据" icon="/static/images/icon/data.jpg">
        </u-empty>
      </view>
    </scroll-view>
    <hs-privacyPopup></hs-privacyPopup>
  </view>
</template>

<script>
import {
  getExampleList,
  getStyleList,
  getMaterialList,
  getSkuList,
  typeList,
} from "@/api/custom.js";
import { mapGetters, mapMutations } from "vuex";
import eventTracking from "@/utils/eventTracking.js"; //埋点
import tabbarNoticeMixin from '@/mixins/tabbar-notice'; // 引入tabbarNoticeMixin

export default {
  mixins: [tabbarNoticeMixin], // 使用tabbarNoticeMixin
  data() {
    return {
      isShowSubNav: true, // 是否显示子导航

      tabsList: [
        // {
        //   name: "人像",
        //   index: 1,
        //   type: 1,
        //   children: [
        //     { name: "充气人像", subType: 1 },
        //     { name: "粘土人像", subType: 2 }
        //   ]
        // },
        // {
        //   name: "字母",
        //   index: 3,
        //   type: 3,
        //   children: [
        //     { name: "动物字母", subType: 3 },
        //     { name: "水晶字母", subType: 4 },
        //     { name: "毛绒字母", subType: 5 }
        //   ]
        // },
        // // {
        // //   name: "人像",
        // //   index: 4,
        // //   type: 4,
        // //   children: [
        // //     { name: "人像", subType: 4 },
        // //   ]
        // // },
        // {
        //   name: "地点",
        //   index: 5,
        //   type: 5,
        //   children: [
        //     { name: "云朵地点", subType: 6 },
        //   ]
        // }
      ],
      mainIndex: 0,
      subIndex: 0,
      algorithmName: "",
      pageSize: 20,
      triggered: false,
      isEmpty: false,
      status: "loading",
      exampleList: [{}, {}, {}, {}, {}, {}],
      styleList: [],
      materialList: [],
      activeStyleList: [],
      activeMaterial: "",
      activeMaterialName: "材质",
      // current: 0,
      // listType: 5,//云朵地标
      // listType: 4,//动物字母
      // listType: 3,//字母
      listType: 1,//人像
      _phoneModelId: "",
      inactiveStyle1: {
        color: "#807D7E",
        fontSize: "38rpx",
      },
      activeStyle1: {
        color: "#3C4242",
        fontSize: "38rpx",
        fontWeight: "700",
      },
      exampleListCache: new Set(), // 用于跟踪已加载过的图片
      lastExampleMaterialMap: {}, // 增加最后一次记录的机型和材质，用于优化切换
      _isManualSelect: false, // 是否允许调用接口
    };
  },
  computed: {
    ...mapGetters(["phoneModelId", "getExampleMaterial"]),
  },
  methods: {
    ...mapMutations(["setExampleMaterial"]),
    getTypeList() {
      typeList().then((res) => {
        console.log("typeList", res);
        this.tabsList = res.data;
        this.algorithmName = this.tabsList[this.mainIndex].children[this.subIndex].algorithmName;
      });
    },
    toggleSubNav(index) {
      console.log("toggleSubNav", index);
      this.mainIndex = index;
      this.subIndex = 0;
      this.listType = this.tabsList[this.mainIndex].children[this.subIndex].type;
      this.algorithmName = this.tabsList[this.mainIndex].children[this.subIndex].algorithmName;
      this.getExampleList(); // 触发数据加载
    },

    switchSubTab(subItem) {
      this.subIndex = subItem.index;
      this.listType = this.tabsList[this.mainIndex].children[this.subIndex].type;
      this.algorithmName = this.tabsList[this.mainIndex].children[this.subIndex].algorithmName;
      this.getExampleList(); // 触发数据加载
    },

    // 获取案例列表
    getExampleList(lastSort) {
      let item = this.tabsList[this.mainIndex].children[this.subIndex];
      console.log("111item", item);
      console.log("lastSort", lastSort);
      getExampleList({
        materialMap: {
          10: this.activeMaterial,
          11: this.phoneModelId || uni.getStorageSync("userInfo").phoneModelId,
        },
        // type: this.listType,
        // algorithmName: this.algorithmName,
        type: item.type,
        algorithmName: item.algorithmName,
        styleIds: this.activeStyleList,
        pageSize: this.pageSize,
        lastSort,
      }).then((res) => {
        // this.exampleList = !lastSort
        //   ? res.data
        //   : this.exampleList.concat(res.data);

        // const timestamp = Date.now();
        // const newData = res.data.map((v) => ({
        //   ...v,
        //   imageUrl: `${v.imageUrl}?t=${timestamp}`, // 强制刷新图片
        //   isLoaded: !lastSort
        //     ? false
        //     : this.exampleListCache.has(v.id),
        // }));

        // // 下拉刷新时清空缓存
        // if (!lastSort) this.exampleListCache = new Set();

        // newData.forEach((v) => this.exampleListCache.add(v.id));
        // // 使用vue.set确保响应式更新
        // console.log("asdf", lastSort, !lastSort ,typeof lastSort !== 'undefined');
        // if (typeof lastSort === 'undefined') {//判断 lastSort 是否存在，如果不存在，则执行以下操作 不能使用!lastSort，因为lastSort有可能是0
        //   console.log('lastSort is undefined');
        //   this.exampleList = newData;
        // } else {
        //   const newIds = new Set(newData.map((v) => v.id));
        //   const filteredList = this.exampleList.filter(
        //     (v) => !newIds.has(v.id)
        //   );
        //   console.log('filteredList',filteredList);
        //   this.exampleList = [...filteredList, ...newData];
        // }
        this.exampleList = !lastSort ? res.data : this.exampleList.concat(res.data)
        if (this.exampleList.length == 0) {
          this.isEmpty = true;
          this.status = "nomore";
        } else if (res.data.length < this.pageSize) {
          this.status = "nomore";
          this.isEmpty = false;
        } else {
          this.status = "loadmore";
          this.isEmpty = false;
        }
        this.triggered = false;
      });
    },
    // 下拉刷新
    onRefresh() {
      if (this.triggered) return;
      this.triggered = true;
      setTimeout(() => {
        this.getExampleList();
      }, 500);
    },
    // 复位
    onRestore() {
      this.triggered = false;
    },
    // 滑动到底部
    scrolltolower() {
      if (this.exampleList.length < this.pageSize) return;
      console.log('scrolltolower', this.exampleList[this.exampleList.length - 1].sort),
        this.getExampleList(
          this.exampleList[this.exampleList.length - 1].sort
        );
    },
    // 获取风格列表
    getStyleList() {
      getStyleList({
        type: 2,
      }).then((res) => {
        this.styleList = res.data;
      });
    },
    // 获取机壳列表
    async getMaterialList(phoneModelId) {
      const { data } = await getSkuList({
        materialMap: {
          11: phoneModelId || this.phoneModelId,
        },
        pageSize: 50,
      });
      //   this.$nextTick(() => {
      //     this.materialList = data.data;
      //     let idx = this.materialList.findIndex((item) => {
      //       return this.activeMaterial == item.materialMap[10];
      //     });
      //     idx = idx == -1 ? 0 : idx;
      //     this.selectMaterial(this.materialList[idx], idx);
      //   });

      // 智能匹配策略
      // const idx = data.findIndex(item =>
      // 	storedMaterial?.materialMap[10] === item.materialMap[10]
      // )

      // const finalIndex = idx !== -1 ?
      // 	idx :
      // 	data.findIndex(item => item.defaulted)

      this.materialList = data;
      this.$nextTick(() => {
        const storedMaterial = this.getExampleMaterial;
        let finalIndex = 0;
        if (data.length > 0) {
          // 明确优先级：  历史记录 > 镜面黑边 > 默认项 > 首项
          // 使用可选链和空值合并操作符
          const historyMaterialId = storedMaterial?.materialMap?.[10] ?? null; // 先查找历史记录
          // 分步查找策略
          finalIndex = data.findIndex(
            (i) => i.materialMap?.[10] === historyMaterialId
          );
          console.log('finalIndex', finalIndex);
          // 未找到历史材质时查找默认项为镜面黑边
          if (finalIndex === -1) {
            finalIndex = data.findIndex(item =>
              item.name === '镜面黑边'
            );
          }

          // // 未找到历史材质时查找默认项
          // if (finalIndex === -1) {
          //   finalIndex = data.findIndex((item) => item.defaulted);
          // }

          // 双重保险：当默认项也不存在时取首项
          finalIndex = finalIndex >= 0 ? finalIndex : 0;

          finalIndex = Math.max(finalIndex, 0); // 确保下标不小于0
        }
        this.selectMaterial(data[finalIndex], finalIndex);

      });
    },
    // 切换人像和整图
    // switchTab(e) {
    //   // 增加类型相同判断
    //   if (this.listType === e.type) return;
    //   this.current = e.index;
    //   this.listType = e.type;
    //   // this.onRefresh();
    //   this.getExampleList();
    // },
    // 选择手机型号
    selectModel(data) {
      if (this.phoneModelId === data) { // 增加机型比对
        console.log('机型未变化')
        return
      }
      // this._isManualSelect = true; // 手动切换机型，防止连续触发多次接口
      this._phoneModelId = data;
      this.getMaterialList(data).finally(() => {
        // this._isManualSelect = false
      });
      uni.$u.debounce(() => {
        this.onRefresh();
      });
    },
    // 选择材质
    // selectMaterial(data, index) {
    //   // uni.setStorageSync('defaultMaterial', {
    //   // 	data,
    //   // 	index
    //   // })
    //   this.setCurrentMaterial(data);
    //   this.activeMaterial = data?.materialMap[10];
    //   this.$refs.phoneModel.activeMaterialIndex = index;
    //   if (this.materialList.length > 0) {
    //     this.activeMaterialName = this.materialList[index]?.name;
    //   }
    //   this.$refs.phoneModel.materialListShow = false;
    //   uni.$u.debounce(() => {
    //     this.onRefresh();
    //   });
    // },
    selectMaterial(data, index) {
      // uni.setStorageSync('defaultMaterial', {
      // 	data,
      // 	index
      // })
      console.log('000', data);
      console.log('000id', data.id);
      // 新增容错处理
      const targetIndex = this.materialList.findIndex(item => item.id === data.id)
      if (targetIndex === -1) {
        console.error('材质不存在', { id: data.id })
        return this.$nextTick(() => this.onRefresh())
      }
      this.setExampleMaterial(data)

      this.activeMaterial = data?.materialMap[10]
      // this.$refs.phoneModel.activeMaterialIndex = index
      this.$refs.phoneModel.activeMaterialIndex = data.id
      console.log('000list', this.materialList);
      // console.log('0001',this.materialList[data.id]);
      if (this.materialList.length > 0) {
        // this.activeMaterialName = this.materialList[index]?.name
        let [{ ...item }] = this.materialList.filter((d) => d.name == data.name)
        console.log('item', item);
        this.activeMaterialName = item.name
        console.log('filter', this.activeMaterialName);
        this.$refs.phoneModel.name = item.name
        this.$refs.phoneModel.baseImageUrl = item.baseImageUrl
        this.$refs.phoneModel.frameImageUrl = item.frameImageUrl
        let extraData = item.materialMap
        eventTracking.event('SWITCH_MATERIAL', 'pages/example', extraData)
      }
      this.$refs.phoneModel.materialListShow = false
      uni.$u.debounce(() => {
        this.onRefresh()
      })
    },
    onTabItemTap(e) {
      // this.lastExampleMaterialMap = this.getExampleMaterial?.materialMap ?? {}; //切换底部tab栏时，保存上一次的材质
      eventTracking.event('AI_CUSTOMIZATION', e.pagePath,);
    },
    handleImageLoad(item) {
      // 增加空值检查
      if (!item) {
        console.error('Invalid item in handleImageLoad');
        return;
      }
      this.$set(item, "isLoaded", true);
    },

    getRefreshes() {
      // 获取存储数据
      const storedMaterial = this.getExampleMaterial;
      console.log("currentMaterial", storedMaterial);
      this.$nextTick(async () => {
        await this.getMaterialList(); // 等待材质列表加载
        console.log("currentMaterial2", this.materialList);
        if (storedMaterial && this.materialList.length > 0) {
          const validIndex = this.materialList.findIndex(
            (item) => item.materialMap?.[10] === storedMaterial.materialMap?.[10]
          );
          if (validIndex > -1) {
            this.selectMaterial(this.materialList[validIndex], validIndex);
          }
        }
      });
    },


  },
  onLoad() {
    // 初始记录当前机型和材质
    this.lastExampleMaterialMap = this.getExampleMaterial?.materialMap ?? {};
    uni.$u.debounce(() => {
      this.getTypeList();
      this.getMaterialList();
    });
  },
  onHide() {
    this.lastExampleMaterialMap = this.getExampleMaterial?.materialMap ?? {}; //切换底部tab栏时，保存上一次的材质
  },
  onShow() {


    const currentMaterialMap = this.getExampleMaterial.materialMap; // 当前机型和材质
    const lastMap = this.lastExampleMaterialMap || {}; // 增加空对象保护
    // 安全读取键值（使用空值合并运算符）
    const current10 = currentMaterialMap[10] ?? null;
    const last10 = lastMap[10] ?? null;
    // 精确比较关键字段（材质ID 10和机型ID 11）

    if (current10 !== last10) {
      console.log('关键材质变化，自动刷新');
      this.getRefreshes();
      uni.$u.debounce(() => {
        this.getMaterialList();
      });
    }

    // 增加严格相等判断
    // if(JSON.stringify(this.lastExampleMaterialMap) !== JSON.stringify(currentMaterialMap)) {
    //   console.log('材质变化，自动刷新');
    //   this.getRefreshes();
    // }

    // 机型变化检测
    // if(Object.keys(this.lastExampleMaterialMap).length !== 0 && (this.lastExampleMaterialMap[10] !== currentMaterialMap[10] || this.lastExampleMaterialMap[11] !== currentMaterialMap[11] ) ) {
    // 	console.log('检测到机型变化，自动刷新');
    // 	this.getRefreshes(); // 触发下拉刷新
    // }else{
    // 	console.log('机型未变化，无需刷新');
    // }
    // 记录当前机型
    this.lastExampleMaterialMap = { ...currentMaterialMap }; // 深度克隆避免引用关联

  },
  // onShow() {
  // 	if (this._phoneModelId != this.phoneModelId) {
  // 		this.selectModel(this.phoneModelId)
  // 	}

  // 	console.log('currentMaterial',this.getCurrentMaterial);
  // 	if(this.getCurrentMaterial){
  // 		this.selectMaterial(this.getCurrentMaterial)
  // 		return
  // 	}

  // 	// let defaultMaterial = uni.getStorageSync('defaultMaterial')
  // 	// if (defaultMaterial && defaultMaterial.data) {
  // 	// 	this.selectMaterial(defaultMaterial.data, defaultMaterial.index)
  // 	// 	uni.removeStorageSync('defaultMaterial')
  // 	// }
  // },
  onShareAppMessage() {
    return {
      title: "我发现了一款可以DIY定制手机壳的小程序，快来看看吧",
      path: `/pages/index/index?page=example`,
    };
  },
  watch: {
    phoneModelId(newVal, oldVal) {
      // if (this._isManualSelect || newVal === oldVal) return; // 防止重复触发
      if (newVal === oldVal) return; // 防止重复触发
      this.getMaterialList(newVal).then(() => {
        const hasPrevious = this.materialList.some(
          (item) =>
            item.materialMap[10] === this.getExampleMaterial?.materialMap[10]
        );

        if (!hasPrevious) {
          this.setExampleMaterial(
            this.materialList.find((item) => item.defaulted)
          );
        }
      });
    },
  },
  // onShareTimeline() {
  // 	return {
  // 		title: '我发现了一款可以DIY定制手机壳的小程序，快来看看吧',
  // 		path: `/pages/index/index?page=example`,
  // 	}
  // }
};
</script>

<style lang="scss">
.index-page {
  display: flex;
  flex-direction: column;
  height: 100%;

  .tabs {
    margin: 0rpx auto 50rpx; //使列表往下移
    position: relative;
    width: 336rpx;

    .nav-container {
      position: relative;
      z-index: 10;

      .primary-nav {
        display: flex;
        justify-content: center;
        background: #fff;
        width: 100vw;

        .nav-item {
          padding: 20rpx 30rpx;
          font-size: 36rpx;
          position: relative;
          transition: all 0.3s;
          display: flex;
          flex-direction: row;

          &.active {
            color: #3C4242;
            font-weight: bold;
          }
        }
      }

      .sub-nav {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: #fff;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
        padding: 5rpx 20rpx;
        display: flex;
        flex-wrap: wrap;

        .sub-nav-item {
          padding: 5rpx 24rpx;
          margin: 5rpx;
          background: #f5f5f5;
          border-radius: 40rpx;
          font-size: 26rpx;

          &:hover {
            background: #e0e0e0;
          }
        }

        .sub-active {
          background: #3C4242 !important;
          color: white !important;

          &::after {
            content: '✓';
            margin-left: 8rpx;
          }
        }
      }
    }

    /* display: block !important;
        width: 100%;
        min-width: 100%;  
        overflow-x: auto;  
        
        /deep/ .u-tabs {
            flex-wrap: nowrap;  
            width: auto;  
            min-width: 100%;  
        }
        
        /deep/ .u-tabs__wrapper {
            white-space: nowrap;  
        } */
  }

  .scroll-box {
    height: 100%;
    flex: 1;
    overflow: hidden;

    // .material-content {
    // 	display: flex;
    // 	padding: 10rpx;
    // 	background-color: #fff;
    // 	position: relative;

    // 	.phone-model {
    // 		height: 50rpx;
    // 		line-height: 50rpx;
    // 		font-size: 28rpx;
    // 		margin: 26rpx 35rpx 0;
    // 		position: relative;
    // 		color: #979797;
    // 		flex-shrink: 0;

    // 		.phone-select {
    // 			display: inline-block;
    // 			border-radius: 50rpx;
    // 			border: 2rpx solid #333;
    // 			padding: 0 17rpx;
    // 			font-size: 26rpx;
    // 			height: 50rpx;

    // 			text {
    // 				font-weight: bold;
    // 				color: #333;
    // 			}

    // 			.text1 {
    // 				margin-left: 17rpx;
    // 				font-size: 20rpx;
    // 			}
    // 		}
    // 	}

    // 	.material-name {
    // 		height: 100rpx;
    // 		display: flex;
    // 		flex-grow: 1;

    // 		image {
    // 			height: 100%;
    // 			width: 100rpx;
    // 			position: absolute;
    // 		}

    // 		text {
    // 			font-size: 28rpx;
    // 			margin: auto;
    // 			margin-left: 100rpx;
    // 		}

    // 		.text1 {
    // 			margin-left: 17rpx;
    // 			font-size: 20rpx;
    // 		}
    // 	}

    // 	.material-list {
    // 		height: 300rpx;
    // 		width: 100%;
    // 		background-color: #fff;
    // 		position: absolute;
    // 		bottom: -300rpx;
    // 		left: 0;
    // 		z-index: 999;
    // 		box-shadow: -1rpx 10rpx 17rpx -7rpx #666;

    // 		.material-scroll {
    // 			display: flex;

    // 			.material-item {
    // 				height: 280rpx;
    // 				width: 25vw;
    // 				background-color: #fff;
    // 				border-radius: 17rpx;
    // 				overflow: hidden;
    // 				display: flex;
    // 				flex-direction: column;
    // 				position: relative;
    // 				margin-right: 30rpx;
    // 				text-align: center;
    // 				flex-shrink: 0;

    // 				&.active {
    // 					opacity: 0.7;

    // 					.radio {
    // 						position: absolute;
    // 						right: 17rpx;
    // 						top: 17rpx;
    // 						z-index: 1;
    // 					}
    // 				}

    // 				.image {
    // 					width: 100%;
    // 					height: 280rpx;
    // 					background: #fff;
    // 					position: relative;

    // 					image {
    // 						width: 100%;
    // 						height: 100%;
    // 						position: absolute;
    // 						top: 0;
    // 						left: 0;
    // 					}
    // 				}

    // 				.title {
    // 					font-size: 24rpx;
    // 					margin: 17rpx;
    // 					flex-shrink: 0;
    // 					flex-grow: 0;
    // 					height: 50rpx;
    // 				}

    // 				.item-btn {
    // 					height: 65.8rpx;
    // 					border-radius: 17rpx;
    // 					font-size: 30rpx;
    // 					box-sizing: border-box;
    // 					text-align: center;
    // 					line-height: 62.8rpx;
    // 					background-color: #333;
    // 					color: #fff;
    // 					margin: 17rpx;
    // 				}
    // 			}
    // 		}

    // 	}
    // }

    .cases {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      // grid-gap: 20rpx;
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 14px 23rpx;
      background-color: #fff;

      .cases-item {
        width: 343rpx;
        height: 416.5rpx;
        border-radius: 12px 12px 0px 0px;
        overflow: hidden;

        .img {
          height: 343rpx;
          width: 343rpx;
          background-color: #eee;
        }

        .price {
          font-size: 28rpx;
          text-align: center;
        }
      }
    }

  }
}
</style>
